<template>
  <div class="base-echarts" ref="baseEchartsRef" :style="{ width, height }"></div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch, withDefaults } from 'vue'
import * as echarts from 'echarts'

const baseEchartsRef = ref<HTMLElement>()

const props = withDefaults(
  defineProps<{
    width?: string
    height?: string
    options: echarts.EChartsOption
  }>(),
  {
    width: '100%',
    height: '100%',
    options: () => ({}),
  },
)

let echartsInstance: echarts.ECharts | null = null
onMounted(() => {
  if (baseEchartsRef.value) {
    echartsInstance = echarts.init(baseEchartsRef.value, null, { renderer: 'svg' })
    echartsInstance.setOption(props.options)
  }
})

watch(
  () => props.options,
  (newValue) => {
    if (echartsInstance) {
      echartsInstance.setOption(newValue)
    }
  },
  { deep: true },
)

onUnmounted(() => {
  if (echartsInstance) {
    echartsInstance.dispose() // 销毁实例
  }
})
</script>

<style scoped></style>
